package com.ruoyi.open.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.system.domain.SysServerRegiste;
import com.ruoyi.system.service.ISysServerRegisteService;
import com.ruoyi.web.util.RedisKeys;
import com.ruoyi.web.util.TokenGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author ：吉金武
 * @ClassName ExtemalTokenContrroller
 * @date ：2024/4/30 - 16:11
 * @version: V1.0
 * @slogan: 天下风云出我辈，一入代码岁月催
 * @description:
 **/
@RequestMapping("/sys/auto")
@RestController
public class ExternalTokenController {


    @Autowired
    private RedisCache redisUtils;

    @Autowired
    private ISysServerRegisteService sysServerRegisteService;

    @PostMapping("/getAccessToken")
    public AjaxResult getAccessToken(String appId, String appSecret) throws Exception {
        SysServerRegiste sysServerRegisteEntity = sysServerRegisteService.findByAppIdAndAppSecret(appId, appSecret);
        if (sysServerRegisteEntity == null){
            return AjaxResult.error(401,"无权限访问，请联系管理员!");
        }
        String token = TokenGenerator.generateValue();
        //设置token，两小时过期
        redisUtils.setCacheObject(RedisKeys.getAccessTokenKey(sysServerRegisteEntity.getAppId(),sysServerRegisteEntity.getAppSecret()),token,1800, TimeUnit.SECONDS);
        Map<String ,Object> map = new HashMap<>();
        map.put("access_token",token);
        map.put("effective_time",1800);
        return AjaxResult.success(map);
    }
}

